﻿using Faser_Shop.Models.Database;
using Faser_Shop.Models.DTO;
using Faser_Shop.Models.RequestModel;
using Faser_Shop.Services;
using Faser_Shop.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Faser_Shop.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class ShoppingCartsController : Controller
    {
        private readonly Faser_ShopContext _db;
        private readonly IJWTService _jwtService;

        public ShoppingCartsController(Faser_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 加入购物车接口（需授权）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public object AddToShoppingCart([FromBody] AddToShoppingCartRM model)
        {
            var hasProduct = _db.Products.Any(x => x.ProductId == model.ProductId);
            if (!hasProduct)
            {
                return ApiResult.PRODUCT_NOT_FOUND;
            }

            _db.ShoppingCarts.Add(new ShoppingCart()
            {
                UserId = _jwtService.GetUserId(HttpContext),
                ProductId = model.ProductId,
                ProductQuantity = model.ProductQuantity
            });

            var result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.INSERT_FAILED_DB_NOCHANGE;
        }

        /// <summary>
        /// 减少购物车商品数量接口（需授权）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public object ReduceShoppingCart([FromBody] ReduceShoppingCart model)
        {
            var userId = _jwtService.GetUserId(HttpContext);
            var shoppingCart = _db.ShoppingCarts.FirstOrDefault(x => x.CartId == model.CartId && x.UserId == userId);
            if (shoppingCart == null)
            {
                return ApiResult.SHOPPING_CART_NOT_FOUND;
            }

            var freeQuantity = shoppingCart.ProductQuantity - model.ReduceQuantity;
            if (freeQuantity <= 1)
            {
                _db.ShoppingCarts.Remove(shoppingCart);
            }
            else
            {
                shoppingCart.ProductQuantity = freeQuantity;
            }

            var result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.UPDATE_FAILED_DB_NOCHANGE;
        }

        /// <summary>
        /// 删除购物车商品接口（需授权）
        /// </summary>
        /// <param name="cartId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public object DeleteShoppingCart([FromBody] int cartId)
        {
            var userId = _jwtService.GetUserId(HttpContext);
            var shoppingCart = _db.ShoppingCarts.FirstOrDefault(x => x.CartId == cartId && x.UserId == userId);
            if (shoppingCart == null)
            {
                return ApiResult.SHOPPING_CART_NOT_FOUND;
            }

            _db.ShoppingCarts.Remove(shoppingCart);

            var result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.DELETE_FAILED_DB_NOCHANGE;
        }

        /// <summary>
        /// 获取购物车内容（需授权）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public object GetShoppingCart()
        {
            var userId = _jwtService.GetUserId(HttpContext);
            var shoppingCarts = _db.ShoppingCarts.Where(x => x.UserId == userId).ToList();
            var products = _db.Products.ToList();

            var result = shoppingCarts.Select(x => new ShoppingCartDTO()
            {
                CartId = x.CartId,
                ProductId = x.ProductId,
                ProductQuantity = x.ProductQuantity,
                ProductName = products.FirstOrDefault(p => p.ProductId == x.ProductId)?.ProductName,
                ProductPrice = products.FirstOrDefault(p => p.ProductId == x.ProductId)?.ProductPrice
            });

            return ApiResult.Success(result);
        }

    }
}
